<?php

namespace app\admin\model;

use think\facade\Db;

class Strategymodel extends Commonmodel {

    protected $userTable;
    protected $croomTable;
    protected $detailTable;
    protected $equipmentTable;

    public function __construct(array $data = [])
    {
        $this->table = 'zhjs_tactics';
        $this->pk = 'id';
        parent::__construct($data);
        $this->userTable = 'zhjs_user';
        $this->croomTable = 'zhjs_classroom';
        $this->detailTable = 'zhjs_tactics_detail';
        $this->equipmentTable = 'zhjs_tactics_equipment_relation';
    }

    /**
     * 查询文章
     * @param string $type        类型分类(1:图文;2:流媒体;3:课件)
     * @param null $where
     * @param null $pageParam
     * @param int $num
     * @return bool
     */
    public function findAll($type = '1', $where = null, $pageParam = null, $num = 20){
        $whereData = [['c.is_delete' , '=', 1]];
        $paginate = ['list_rows'=>$num];

        if($where)  $whereData = array_merge($where, $whereData);
        if($pageParam = array_splice($pageParam, 1))  $paginate = array_merge($paginate, ['query'=>$pageParam]);

        $select = 'c.id, c.title, c.uid, c.cid, c.crid, c.title, c.create_date, c.examine_status, c.reason, u.username, c.status, cr.name as crname, cr.status as crstatus, cf.name as cfname';

        $data = self::db()
            ->alias('c')
            ->leftJoin([$this->userTable=>'u'],'c.uid=u.id')
            ->leftJoin([$this->croomTable=>'cr'],'c.crid=cr.id')
            ->field($select)
            ->where($whereData)
            ->order(['c.id'=>'desc'])
            ->paginate($paginate);

        if(!$data)  return false;

        $list['page'] = $data->render();
        $dataArr = $data->toArray();
        $list['data'] = $dataArr['data'];

        return $list;
    }

    public function saveInfo($dataArr, $equipmentArr = null, $otherArr, $id = null){
        if(!$dataArr || !$otherArr)  return false;

        if(!$id){
            $dataArr['uid'] = session('adminUserInfo.uid');
        }

        Db::startTrans();
        try {
            if($id){
                $dataArr['examine_status'] = 1;         //内容被修改后，重新进入审核状态待审
                Db::table($this->table)->where(['id'=>$id])->update($dataArr);
                if(session('adminUserInfo.cid')){
                    Db::table($this->detailTable)->where(['id'=>$id, 'crid'=>session('adminUserInfo.cid')])->delete();
                }else{
                    Db::table($this->detailTable)->where([['id', '=', $id], ['crid', '=', 0]])->delete();
                }
                if($equipmentArr && session('adminUserInfo.cid'))  Db::table($this->equipmentTable)->where([['tid', '=', $id], ['crid', '=', session('adminUserInfo.cid')], ['type', '=', $dataArr['screen_type']]])->delete();
                foreach($otherArr as $key=>$val){
                    if(session('adminUserInfo.cid')){
                        if($val['crid']){
                            $otherArr[$key]['type'] = 2;
                            $otherArr[$key]['id'] = $id;
                        }else{
                            unset($otherArr[$key]);
                        }
                    }else{
                        $otherArr[$key]['id'] = $id;
                    }
                }
            }else{
                $dataArr['uid'] = session('adminUserInfo.uid');
                Db::table($this->table)->save($dataArr);
                $id = Db::table($this->table)->getLastInsID();
                foreach($otherArr as $key=>$val){
                    if(session('adminUserInfo.cid')){
                        $otherArr[$key]['type'] = 2;
                        $otherArr[$key]['crid'] = session('adminUserInfo.cid');
                    }
                    $otherArr[$key]['id'] = $id;
                }
            }
            if($equipmentArr && session('adminUserInfo.cid')){
                $newDataArr = [];
                foreach($equipmentArr as $key=>$val){
                    $newDataArr[$key]['tid'] = $id;
                    $newDataArr[$key]['eid'] = $val;
                    $newDataArr[$key]['type'] = $dataArr['screen_type'];
                    $newDataArr[$key]['crid'] = session('adminUserInfo.cid');
                }
                Db::table($this->equipmentTable)->insertAll($newDataArr);
            }
            Db::table($this->detailTable)->insertAll($otherArr);
            Db::commit();
            return $id;
        } catch (\Exception $e) {
            trace('(saveInfo)保存\修改失败，添加内容为：' . json_encode($dataArr) . '失败原因：' . $e->getMessage(), 'error');
            Db::rollback();
            return false;
        }
    }

    /**
     * 查询文章内容
     * @param string $select
     * @param null $id
     * @param bool $is_detail
     * @param null $where
     * @return bool
     */
    public function findDetaiById($select=  "*", $id = null, $is_detail = true, $where = null){
        if(!$id && !$where)  return false;if(!$id && !$where)  return false;

        if($is_detail){
            $otherTbale = $this->detailTable;
        }else{
            $otherTbale = $this->videoTable;
        }
        $select = 'o.*, c.*';

        $info = self::db()
            ->alias('c')
            ->leftJoin([$otherTbale=>'o'],'o.id=c.id')
            ->field($select)
            ->where(['c.id'=>$id])
            ->find()->toArray();

        if($info)  return $info;
        return false;
    }

    public function getTacticsDetailById($id){
        if(!$id)  return false;
        if(session('adminUserInfo.cid')){
            $whereExp = "d.crid = ".session('adminUserInfo.cid')." or d.crid = 0";
        }else{
            $whereExp = "d.crid = 0";
        }
        $listObj = Db::table($this->detailTable)
            ->alias('d')
            ->leftJoin(['zhjs_content'=>'c'], 'c.id=d.cid')
            ->field('d.*, c.title')
            ->where(['d.id'=>$id])
            ->whereExp('', $whereExp)
            ->select();

        if(!$listObj)  return false;
        return $listObj->toArray();
    }

    //选择本教室下指定设备类型关联策略设备
    public function getTacticsEquipmentRelation($id, $screen_type)
    {
        if(!$id || !$screen_type)  return false;
        $listObj = Db::table($this->equipmentTable)
            ->field('eid')
            ->where(['tid'=>$id, 'crid'=>session('adminUserInfo.cid'), 'type'=>$screen_type])
            ->select();

        if(!$listObj)  return false;
        return reduce($listObj->toArray());
    }


}

?>